//
//  SchoolViewController.swift
//  miaoyin
//
//  Created by David on 2017/2/22.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

@objc protocol SchoolSelectDelegate{
    @objc optional func schoolView(data: Any)
}

class SchoolViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SchoolSelectDelegate {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var delegate: SchoolSelectDelegate?
    
    
    
    var tableView: UITableView!
    var searchBar: UITextField!
    
    var nearData: NSArray?
    var popData: NSArray?
    var searchResult: NSArray?
    
    
//    var regData: String?
//    convenience init(regData: String){
//        self.init()
//        self.regData = regData
//    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "选择学校"
        navigationController?.setNavigationBarHidden(true, animated: false)
        
        let navBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        navBar.barTintColor = themeColor2
        navBar.barStyle = .black
        navBar.tintColor = UIColor.white
        
        
        let navItem = UINavigationItem(title: "选择学校")
        navItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "navbar_back"), style: .plain, target: self, action: #selector(SchoolViewController.goBack))
        
        if FCUserReg.shared.isRegisterStarted{
            navItem.rightBarButtonItem = UIBarButtonItem(title: "跳过", style: .plain, target: self, action: #selector(SchoolViewController.skipRegUserInfo))
        }
        
        navBar.pushItem(navItem, animated: true)
        
        tableView = UITableView(frame: CGRect(x: 0, y: 44, width: view.frame.width, height: view.frame.height - 44))
        tableView.delegate = self
        tableView.dataSource = self
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.keyboardDismissMode = .onDrag
        view.addSubview(tableView)
        
        let headerView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44))
        headerView.backgroundColor = UIColor.groupTableViewBackground
        
        searchBar = UITextField(frame: CGRect(x: 16, y: 8, width: view.bounds.width - 32, height: 28))
        searchBar.font = UIFont.systemFont(ofSize: 14)
        searchBar.placeholder = "搜索学校名称"
        searchBar.backgroundColor = UIColor.white
        searchBar.layer.cornerRadius = 4
        searchBar.returnKeyType = .search
        searchBar.enablesReturnKeyAutomatically = true
        searchBar.clearButtonMode = .always
        headerView.addSubview(searchBar)
        searchBar.addTarget(self, action: #selector(SchoolViewController.searchBarFinish), for: .editingDidEndOnExit)
        searchBar.addTarget(self, action: #selector(SchoolViewController.searchBarEnd), for: .editingDidEnd)
        
        tableView.tableHeaderView = headerView
        
        view.addSubview(navBar)
        
        loadNearSchool()
        loadPopSchool()
        
    }
    
    func loadNearSchool(){
        print( "\(Fatcat.SERVER_DOMAIN_NAME)/index.php?m=admin&c=user&a=schoolinfo&t=1")
        let url = URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)/index.php?m=admin&c=user&a=schoolinfo&t=1")!
        URLSession.shared.dataTask(with: url) { (data:Data?, resp:URLResponse?, err:Error?) in
            do{
                if err != nil{
                    throw err!
                }
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                self.nearData = jsonObj?.object(forKey: "data") as? NSArray
                DispatchQueue.main.async {
                    self.tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .automatic)
                }
            }catch let ex{
                print(ex)
            }
            
        }.resume()
    }
    func loadPopSchool(){
        let url = URL(string: "\(Fatcat.SERVER_DOMAIN_NAME)/index.php?m=admin&c=user&a=schoolinfo&t=2")!
        URLSession.shared.dataTask(with: url) { (data:Data?, resp:URLResponse?, err:Error?) in
            do{
                if err != nil{
                    throw err!
                }
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                self.popData = jsonObj?.object(forKey: "data") as? NSArray
                DispatchQueue.main.async {
                    self.tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .automatic)
                }
            }catch let ex{
                print(ex)
            }
            
        }.resume()
    }
    
    func searchBarEnd(){
        if searchBar.text == "" {
            searchResult = nil
            tableView.reloadData()
        }
    }
    
    func searchBarFinish(){
        searchBar.resignFirstResponder()
        if searchBar.text != "" {
            searchSchool()
            
        }
    }
    
    func searchSchool(){
        //http://114.215.105.95/print/index.php?m=admin&c=user&a=searchSchools&n=关键词
        let rawUrlstr = "\(Fatcat.SERVER_DOMAIN_NAME)/index.php?m=admin&c=user&a=searchSchools&n=\(searchBar.text!)"
        let urlstr = rawUrlstr.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
        if urlstr == nil{
            return
        }
        let url = URL(string: urlstr!)!
        URLSession.shared.dataTask(with: url) { (data:Data?, resp:URLResponse?, err:Error?) in
            do{
                if err != nil{
                    throw err!
                }
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                self.searchResult = jsonObj?.object(forKey: "data") as? NSArray
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }catch let ex{
                print(ex)
            }
            
        }.resume()
    }
    
    func skipRegUserInfo(){
        if FCUserReg.shared.isRegisterStarted{
            FCUserReg.shared.initCommitUserInfo(successHandler: { (data) in
                DispatchQueue.main.async {
                    self.dismiss(animated: true, completion: nil)
                }
                
            }, failedHandler: { (err) in
                print(err ?? "")
                DispatchQueue.main.async {
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    self.present(alert, animated: true, completion: nil)
                }
                
            })
        }
    }
    
    func goBack(){
        if FCUserReg.shared.isRegisterStarted{
//            FCUserReg.shared.wodeVC?.loadUserData()
            
        }
        _ = navigationController?.popViewController(animated: true)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return searchResult != nil ? 1 : 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            if searchResult != nil{
                if searchResult!.count > 0{
                    return searchResult!.count
                }else{
                    return 1
                }
            }else if nearData != nil{
                if nearData!.count > 0{
                    return nearData!.count
                }else{
                    return 1
                }
            }
        }
        if section == 1{
            return popData?.count ?? 0
        }
        return 0
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        if section == 0 {
            return searchResult == nil ? "附近学校" : "\"\(searchBar.text!)\"的结果"
        }
        if section == 1{
            return "热门学校"
        }
        return nil
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        if indexPath.section == 0{
            if searchResult != nil{
                if searchResult!.count > 0{
                    let schoolData = searchResult?.object(at: indexPath.row) as? NSDictionary
                    cell.textLabel?.text = schoolData?.object(forKey: "name") as? String
                }else{
                    cell.textLabel?.text = "未能找到相关学校"
                }
                
            }else if nearData != nil{
                
                if nearData!.count > 0{
                    let schoolData = nearData?.object(at: indexPath.row) as? NSDictionary
                    cell.textLabel?.text = schoolData?.object(forKey: "name") as? String
                }else{
                    cell.textLabel?.text = "未能找到相关学校"
                }
                
                
            }
        }
        
        if indexPath.section == 1{
            let schoolData = popData?.object(at: indexPath.row) as? NSDictionary
            cell.textLabel?.text = schoolData?.object(forKey: "name") as? String
        }
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0{
            if searchResult != nil{
                if searchResult!.count > 0{
                    let data = searchResult?.object(at: indexPath.row)
                    if data != nil{
                        selectSchool(data!)
                    }
                    
                }
            }else if nearData != nil{
                if nearData!.count > 0{
                    let data = nearData?.object(at: indexPath.row)
                    if data != nil{
                        selectSchool(data!)
                    }
                }
            }
        }
        
        if indexPath.section == 1{
            if popData != nil{
                if popData!.count > 0{
                    let data = popData?.object(at: indexPath.row)
                    if data != nil{
                        selectSchool(data!)
                    }
                }
            }
        }
        
    }
    
    var selectedSchoolData: Any?
    
    func selectSchool(_ withData: Any){
        selectedSchoolData = withData
        let majorVC = MajorViewController(schoolData: withData)
        majorVC.delegate = self
        if FCUserReg.shared.isRegisterStarted{
            let schoolID = (withData as? NSDictionary)?.object(forKey: "id") as? String
            if schoolID != nil{
                FCUserReg.shared.univsId = schoolID
            }
            
        }
        hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(majorVC, animated: true)
//        delegate?.schoolView(self, data: withData)
//        _ = navigationController?.popViewController(animated: true)
        
    }
    
    func schoolView(data: Any) {
        
        if !FCUserReg.shared.isRegisterStarted{
            let majorData = data as? NSDictionary
            if majorData != nil{
                let schoolMajorData = NSMutableDictionary()
                schoolMajorData.setValue(majorData!, forKey: "major")
                let schoolData = selectedSchoolData as? NSDictionary
                if schoolData != nil{
                    schoolMajorData.setValue(schoolData!, forKey: "school")
                    _ = navigationController?.popViewController(animated: true)
                    delegate?.schoolView?(data: schoolMajorData)
                    
                }
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
